import React, { useEffect, useState } from "react"
import './index.less'
// 表格组建
type TableType = {
  list: []
  columns?: []
  children?: React.ReactNode
}
function Table(props: TableType) {
  const { list, columns, children } = props
  const [listData, setListData] = useState([])

  // 表格数据聚合方法
  const handleTabel = () => {
    let data = []
    let key = [] as Array<string>
    if (!Array.isArray(list)) return
    list?.forEach((req) => {
      key = Object.keys(req);
    })

    columns?.forEach(res => {
      if (key?.includes(res?.dataIndex)) {
        data?.push({ level: list?.map(req => req), name: res?.title, dataIndex: res?.dataIndex })
        return
      }
      data?.push({ name: res?.title, ...res })
    })
    setListData(data)
  }

  useEffect(() => {
    if (columns?.length > 0) {
      handleTabel()
    }
  }, [columns, list])
  return (
    <div className="table-flex">
      {
        listData?.map((res, index) => {
          return (
            <div key={index} className={`${res?.width || 'table-item'} ${res?.isButtom ? 'table-item-buttom' : ''} table-item-box`}>
              <div>
                {res?.name || ''}
              </div>

              <div className="table-level-box">
                {
                  res?.level?.map((req, indexItem) => {
                    return (
                      <div key={indexItem} className="table-level-item">
                        {children ? children : req[res.dataIndex]}
                      </div>
                    )
                  })
                }
              </div>
            </div>
          )
        })
      }
    </div>
  )
}

export default Table